﻿using KiWing.Business;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using RutarBackgroundServices.AppsettingsJson;
using System.Text.Json;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace webapi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class LotteryPersonController : ControllerBase
    {
       static String connectionString= AppSettingsJson.GetAppSettings().GetConnectionString("LotteryDatabase");

        Business b = new BusinessLogic(connectionString);

        private readonly ILogger<LotteryPersonController> _logger;
        public LotteryPersonController(ILogger<LotteryPersonController> logger)
        {
            _logger = logger;
        }
        // GET: api/<LotteryPersonController>
        [HttpGet(Name = "GetLotteryPerson")]
        public List<Object> Get()
        {
            //查询签到参与抽奖人员 
            List<LotteryPerson> ls= b.Select<LotteryPerson>(new LotteryPerson() { IsParticipator = 2 });
            List<Object> result = new List<object>();
            foreach (LotteryPerson l in ls)
            {
                result.Add(new { phone=l.Phone,name=l.FullName,avatar=l.Avatar});
            }
            return result;
        }

        // POST api/<LotteryPersonController>
        [HttpPost(Name ="Post")]
        public String Post(string fullname,string phone)
        {
            ResultMessage result = new ResultMessage() { Message = "报名失败", Code = 202 };
            try
            {
               List<LotteryPerson> ls= b.Select<LotteryPerson>(new LotteryPerson(){ FullName = fullname,Phone= phone});
                if (ls.Count > 0)
                {
                    LotteryPerson p = ls[0];
                    p.IsParticipator = 1;//报名
                    int id = b.Save<LotteryPerson>(p);
                    if (id > 0)
                    {
                        result.Message = "报名成功";
                        result.Code = 200;
                        return JsonConvert.SerializeObject(result);
                    }
                }
            }
            catch (Exception e)
            {
                result.Message=e.Message;                
            }
            return JsonConvert.SerializeObject(result);

        }

        // PUT api/<LotteryPersonController>/5
        [HttpPut]
        public void Put(LotteryPerson value)
        {

            try
            {
                LambdaQuery<LotteryPerson> query = new LambdaQuery<LotteryPerson>(connectionString, "", "");


            }
            catch (Exception e)
            { 
            
            }
        }

        // DELETE api/<LotteryPersonController>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
